<template>
  <div id="todoList">
    <div>
      <input v-model="inputValue"/>
      <button @click="handleAdd">添加待办事项</button>
    </div>
    <p>v-for list</p>
    <ol>
      <li v-for="(item, index) of todoList" :key="index">{{item}}</li>
    </ol>
    <p>组件形式的list</p>
    <ol>
      <todo-item v-for="(item, index) of todoList" :key="index"
                 :content="item" :index="index"
                 @deleteItem="deleteItem">
      </todo-item>
    </ol>
    <p>fetch</p>
    <button @click="fetchData">请求数据</button>
    <ul>
      <ProductItem v-for="item of productList" :key="item.id" :product="item"/>
    </ul>
    <p>products 总量为： {{totalNum}}</p>
  </div>
</template>

<script>
import TodoItem from './components/TodoItem'
import ProductItem from './components/ProductItem'

export default {
  components: {ProductItem, TodoItem},
  comments: {
    'todo-item': TodoItem,
    ProductItem
  },
  data: function () {
    return {
      inputValue: '',
      todoList: [],
      productList: []
    }
  },
  computed: {
    totalNum () {
      return this.productList.reduce((sum, product) => {
        return sum + product.num
      }, 0)
    }
  },
  methods: {
    handleAdd: function () {
      // this的指向问题：会在$data/$computed/$methods里面去找todoList变量
      this.todoList.push(this.inputValue)
      this.inputValue = ''
    },
    deleteItem (index) {
      this.todoList.splice(index, 1)
    },
    fetchData () {
      fetch('http://localhost:8080/static/api/products.json')
        .then(response => response.json())
        .then(json => {
          this.productList = json
        })
    }
  }
}
</script>

<style>

</style>
